package org.dctmcommons;

import java.util.UUID;

import org.dctmcommons.impl.TeardownBuilder;
import org.junit.*;

import com.documentum.fc.client.IDfDocument;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.common.DfDocbaseConstants;
import com.documentum.fc.common.DfException;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

/**
 * Integration tests for {@link TeardownBuilder}.
 * @author Mark Davidson
 */
public class TeardownBuilderIT {

	/**
	 * Tests path building.
	 * @throws DfException The repository exception
	 */
	@Test
	public void testBuild() throws DfException {
		System.out.println(">>> testBuild");
		
		String testFolderPath = null;
		final IDfSession session = DctmCommonsTestUtil.getSession();
		session.beginTrans();
		
		try {
			testFolderPath = DctmCommonsTestUtil.createTestFolderPath();
			System.out.println("Got test folder path: " + testFolderPath);
			
			for (int i = 0; i <= 3; i++) {
				final IDfFolder folder = createTestFolder(session,
														  testFolderPath);
				final IDfDocument doc = createTestDocument(
												session,
												folder.getObjectId().getId());
				assertThat("Document is null", doc, is(notNullValue()));
			}
			
			session.commitTrans();
		} catch (DfException e) {
			session.abortTrans();
		}
		
		TeardownBuilder.from(testFolderPath)
					   .includeAllObjects()
					   .build(session);
		
		assertThat("Test folder still exists",
				   session.getFolderByPath(testFolderPath),
				   is(nullValue()));
		
		DctmCommonsTestUtil.releaseSession();
	}
	
	/**
	 * Creates a document.
	 * @param session The session
	 * @param linkRef The link reference
	 * @return The document
	 * @throws DfException The repository exception
	 */
	private IDfDocument createTestDocument(final IDfSession session,
										   final String linkRef)
		throws DfException {
		final IDfDocument doc = (IDfDocument) session.newObject(
											DfDocbaseConstants.DM_DOCUMENT);
		doc.setObjectName(UUID.randomUUID().toString());
		doc.save();
		return doc;
	}

	/**
	 * Creates a folder.
	 * @param session The session
	 * @param linkRef the link reference
	 * @return The folder
	 * @throws DfException The repository exception
	 */
	private IDfFolder createTestFolder(final IDfSession session,
									   final String linkRef)
		throws DfException {
		final IDfFolder folder = (IDfFolder) session.newObject(
											DfDocbaseConstants.DM_FOLDER);
		folder.setObjectName(UUID.randomUUID().toString());
		folder.save();
		return folder;
	}
	
	/**
	 * Setup routine.
	 */
	@Before
	public void before() throws DfException {
	}
	
	/**
	 * Teardown routine.
	 */
	@After
	public void after() throws DfException {
	}
	
}
